package com.emm.yixun.website.controller.estate;

//框架包
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.system.service.pmo.PmoDynamicDataServiceFacade;
import com.emm.yixun.system.service.pmo.PmoStaticDataServiceFacade;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.enums.ProjectRoleEnums;
import com.emm.yixun.common.model.Area;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.LevelStaticSalesData;
import com.emm.yixun.common.model.LevelStaticSalesDataChild;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectImg;
import com.emm.yixun.common.model.ProjectInfo;
import com.emm.yixun.common.model.ProjectList;
import com.emm.yixun.common.model.ProjectPmo;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectPremisesIndustData;
import com.emm.yixun.common.model.ProjectPremisesIndustDataVersion;
import com.emm.yixun.common.model.ProjectProcdef;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Role;
import com.emm.yixun.common.model.SaleReturnPmo;
import com.emm.yixun.common.model.StaticSalesData;
import com.emm.yixun.common.model.StaticSalesIndustData;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.AreaDto;
import com.emm.yixun.common.model.dto.MearchantProcdefDto;
import com.emm.yixun.common.model.dto.MerchantDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.dto.ProjectImgDto;
import com.emm.yixun.common.model.dto.ProjectInfoDto;
import com.emm.yixun.common.model.dto.ProjectListDto;
import com.emm.yixun.common.model.dto.ProjectPmoDto;
import com.emm.yixun.common.model.dto.ProjectPremisesDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataVersionDto;
import com.emm.yixun.common.model.dto.ProjectProcdefDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.RoleDto;
import com.emm.yixun.common.model.dto.RootClass;
import com.emm.yixun.common.model.dto.SaleReturnPmoDto;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.estate.service.ProjectImgServiceFacade;
import com.emm.yixun.estate.service.ProjectInfoServiceFacade;
import com.emm.yixun.estate.service.ProjectPmoServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataVersionServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectProcdefServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.estate.service.ProjectSettingServiceFacade;
import com.emm.yixun.estate.service.SaleReturnPmoServiceFacade;
import com.emm.yixun.marketing.service.SalesGroupUserServiceFacade;
import com.emm.yixun.system.service.AreaServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.MearchantProcdefServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.RoleServiceFacade;
import com.emm.yixun.system.service.UserProjectServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.system.service.pmo.LevelStaticSalesDataServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.estate.ProjectPremisesIndustDataService;
import com.emm.yixun.website.service.pmo.LevelProjectDataService;
import com.emm.yixun.website.service.pmo.LevelStaticSalesDataService;
import com.emm.yixun.website.vo.estate.LevelData;
import com.emm.yixun.website.vo.estate.ProjectInfoVo;
import com.emm.yixun.website.vo.estate.ProjectSettingVo;
import com.emm.yixun.website.vo.estate.ProjectVo;
import com.emm.yixun.website.vo.estate.SaleReturnPmoVo;
//变化的引用
//common
//website

import net.sf.json.JSONArray;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

@Controller
@RequestMapping("/estate/project/")
public class ProjectController extends BaseController<Project> {
	private final Logger logger = LoggerFactory.getLogger(ProjectController.class);

	@Autowired
	private ProjectServiceFacade projectServiceFacade;

	@Autowired
	private ProjectInfoServiceFacade projectInfoServiceFacade;

	@Autowired
	private ProjectSettingServiceFacade projectSettingServiceFacade;

	@Autowired
	private AreaServiceFacade areaServiceFacade;

	@Autowired
	private ProjectImgServiceFacade projectImgServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;

	@Resource
	private ProjectPremisesServiceFacade premisesServiceFacade;

	@Resource
	private UserProjectServiceFacade userProjectServiceFacade;

	@Autowired
	private SalesGroupUserServiceFacade salesGroupUserServiceFacade;

	@Autowired
	private RoleServiceFacade roleServiceFacade;

	@Autowired
	private ProjectProcdefServiceFacade projectProcdefServiceFacade;

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private MerchantServiceFacade merchantServiceFacade;

	@Autowired
	private MearchantProcdefServiceFacade mearchantProcdefServiceFacade;

	@Autowired
	private ProjectPmoServiceFacade projectPmoServiceFacade;

	@Autowired
	private LevelStaticSalesDataService levelStaticSalesDataService;

	@Autowired
	private ProjectPremisesIndustDataServiceFacade projectPremisesIndustDataServiceFacade;

	@Autowired
	private SaleReturnPmoServiceFacade saleReturnPmoServiceFacade;

	@Autowired
	private ProjectPremisesIndustDataService projectPremisesIndustDataService;
	@Autowired
	private ProjectPremisesIndustDataVersionServiceFacade premisesIndustDataVersionServiceFacade;
	@Autowired
	private LevelStaticSalesDataServiceFacade levelStaticSalesDataServiceFacade;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private LevelProjectDataService levelProjectDataService;
	@Autowired
	private PmoStaticDataServiceFacade pmoStaticDataServiceFacade;
	@Autowired
	private PmoDynamicDataServiceFacade pmoDynamicDataServiceFacade;

	@RequestMapping(value = "index")
	@MerchantResourcesConfig(resourcesCode = "menu_0003_0001_0005")
	public String index(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			List<com.emm.yixun.common.model.Resources> resourcesList = getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
			map.put("permitBtn", resourcesList);
			map.put("permitBtnJson", JSONArray.fromObject(resourcesList));
			map.put("menu", getPageData().getString("menu"));
			AreaDto areaDto = new AreaDto();
			areaDto.setParentId(Long.valueOf(0));
			ResponseList<Area> responseAreaList = areaServiceFacade.findByDto(areaDto);
			if (responseAreaList.isSuccess() && null != responseAreaList.getEntity()) {
				map.put("areas", responseAreaList.getEntity());
			} else {
				map.put("areas", new ArrayList<Area>());
			}
			return "/estate/projectBasic/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "indexLC")
	public String indexLC(ModelMap map) {
		// 查询菜单按钮权限
		List<com.emm.yixun.common.model.Resources> resourcesList = getPermitBtn(Const.RESOURCES_TYPE_FUNCTION);
		map.put("permitBtn", resourcesList);
		map.put("permitBtnJson", JSONArray.fromObject(resourcesList));
		map.put("menu", getPageData().getString("menu"));
		AreaDto areaDto = new AreaDto();
		areaDto.setParentId(Long.valueOf(0));
		ResponseList<Area> responseAreaList = areaServiceFacade.findByDto(areaDto);
		if (responseAreaList.isSuccess() && null != responseAreaList.getEntity()) {
			map.put("areas", responseAreaList.getEntity());
		} else {
			map.put("areas", new ArrayList<Area>());
		}
		return "/estate/project/list";
	}

	@RequestMapping(value = "toAdd")
	@MerchantResourcesConfig(resourcesCode = "menu_0003_0001_0001")
	public String toAdd(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, ModelMap map,
			Long id) {
		// 产品类型
		map.put("projectTypes", ProjectTypeEnum.values());
		// 项目类型
		map.put("itemTypes", ItemTypesEnum.values());
		// 交付情况
		map.put("deliveryStatusEnums", DeliveryStatusEnum.values());
		// 销售情况
		map.put("salesStatusEnums", SalesStatusEnum.values());
		// 装修标准
		map.put("renovationTypeEnums", RenovationTypeEnums.values());
		User user = ShiroUtil.getCurrentUser();
		String[] roleNames = SysConstants.PROJECT_ROLE_NAME;
		for (int i = 0; i < roleNames.length; i++) {
			RoleDto roleDto = new RoleDto();
			roleDto.setMerchantId(user.getMerchantId());
			roleDto.setRoleName(roleNames[i]);
			ResponseList<Role> roleResponseList = roleServiceFacade.findByDto(roleDto);
			ArrayList<User> userList = new ArrayList<User>();
			if (roleResponseList.isSuccess() && null != roleResponseList.getEntity()) {
				for (Role role : roleResponseList.getEntity()) {
					UserDto dto = new UserDto();
					dto.setMerchantId(user.getMerchantId());
					dto.setUserStatus("0");
					dto.setRoleId(role.getId());
					ResponseList<User> responseList = userServiceFacade.findByDto(dto);
					if (responseList.isSuccess() && null != responseList.getEntity()) {
						userList.addAll(responseList.getEntity());
					}
				}
			}
			if (i == 0) {
				map.put("generalManager", userList);
			} else if (i == 1) {
				map.put("projectLeader", userList);
			} else if (i == 2) {
				map.put("saleLeader", userList);
			} else if (i == 3) {
				map.put("fieldLeader", userList);
			} else if (i == 4) {
				map.put("maLeader", userList);
			} else if (i == 5) {
				map.put("financeLeader", userList);
			} else if (i == 6) {
				map.put("areaLeader", userList);
			} else if (i == 7) {
				map.put("areaManager", userList);
			}

		}

		// 物业类型
		map.put("tenementTypeEnums", TenementTypeEnum.values());
		AreaDto areaDto = new AreaDto();
		areaDto.setParentId(Long.valueOf(0));
		ResponseList<Area> responseAreaList = areaServiceFacade.findByDto(areaDto);
		if (responseAreaList.isSuccess() && null != responseAreaList.getEntity()) {
			map.put("areas", responseAreaList.getEntity());
		} else {
			map.put("areas", new ArrayList<Area>());
		}
		Response<Project> response = projectServiceFacade.findById(id);
		if (response.isSuccess() && response.getEntity() != null) {
			map.put("project", response.getEntity());
			// 查询图片
			ProjectImgDto projectImgDto = new ProjectImgDto();
			projectImgDto.setProjectId(id);
			projectImgDto.setDelFlag("0");
			ResponseList<ProjectImg> responseListImg = projectImgServiceFacade.findByDto(projectImgDto);
			if (responseListImg.isSuccess() && null != responseListImg.getEntity()) {
				map.put("imgList", responseListImg.getEntity());
			}

			ProjectInfoDto projectInfoDto = new ProjectInfoDto();
			projectInfoDto.setProjectId(id);
			ResponseList<ProjectInfo> responseProjectInfo = projectInfoServiceFacade.findByDto(projectInfoDto);
			if (responseProjectInfo.isSuccess() && null != responseProjectInfo.getEntity()
					&& responseProjectInfo.getEntity().size() > 0) {
				map.put("projectInfo", responseProjectInfo.getEntity().get(0));
			}

			ProjectSettingDto projectSettingDto = new ProjectSettingDto();
			projectSettingDto.setProjectId(id);
			ResponseList<ProjectSetting> setResponseList = projectSettingServiceFacade.findByDto(projectSettingDto);
			if (setResponseList.isSuccess() && null != setResponseList.getEntity()
					&& setResponseList.getEntity().size() > 0) {
				map.put("projectSetting", setResponseList.getEntity().get(0));
			} else {
				map.put("projectSetting", new ProjectSetting());
			}
		}
		return "/estate/projectBasic/form";
	}

	@RequestMapping(value = "toLCAdd")
	public String toLCAdd(ModelMap map, Long id) {
		String month = DateUtils.DateToString(new Date(), DateStyle.YYYYMM);
		HashMap<String, BigDecimal> dynamiMap = projectServiceFacade.queryDynamiValue(id, null, month, "0");
		map.put("dynamiMap", dynamiMap);
		// 产品类型
		map.put("projectTypes", ProjectTypeEnum.values());
		// 项目类型
		map.put("itemTypes", ItemTypesEnum.values());
		// 交付情况
		map.put("deliveryStatusEnums", DeliveryStatusEnum.values());
		// 销售情况
		map.put("salesStatusEnums", SalesStatusEnum.values());
		// 装修标准
		map.put("renovationTypeEnums", RenovationTypeEnums.values());
		User user = ShiroUtil.getCurrentUser();
		String[] roleNames = SysConstants.PROJECT_ROLE_NAME;
		for (int i = 0; i < roleNames.length; i++) {
			RoleDto roleDto = new RoleDto();
			roleDto.setMerchantId(user.getMerchantId());
			roleDto.setRoleName(roleNames[i]);
			ResponseList<Role> roleResponseList = roleServiceFacade.findByDto(roleDto);
			ArrayList<User> userList = new ArrayList<User>();
			if (roleResponseList.isSuccess() && null != roleResponseList.getEntity()) {
				for (Role role : roleResponseList.getEntity()) {
					UserDto dto = new UserDto();
					dto.setMerchantId(user.getMerchantId());
					dto.setUserStatus("0");
					dto.setRoleId(role.getId());
					ResponseList<User> responseList = userServiceFacade.findByDto(dto);
					if (responseList.isSuccess() && null != responseList.getEntity()) {
						userList.addAll(responseList.getEntity());
					}
				}
			}
			if (i == 0) {
				map.put("generalManager", userList);
			} else if (i == 1) {
				map.put("projectLeader", userList);
			} else if (i == 2) {
				map.put("saleLeader", userList);
			} else if (i == 3) {
				map.put("fieldLeader", userList);
			} else if (i == 4) {
				map.put("maLeader", userList);
			} else if (i == 5) {
				map.put("financeLeader", userList);
			} else if (i == 6) {
				map.put("areaLeader", userList);
			} else if (i == 7) {
				map.put("areaManager", userList);
			}

		}

		map.put("tenementTypeEnums", TenementTypeEnum.values());
		AreaDto areaDto = new AreaDto();
		areaDto.setParentId(Long.valueOf(0));
		ResponseList<Area> responseAreaList = areaServiceFacade.findByDto(areaDto);
		if (responseAreaList.isSuccess() && null != responseAreaList.getEntity()) {
			map.put("areas", responseAreaList.getEntity());
		} else {
			map.put("areas", new ArrayList<Area>());
		}
		Response<Project> response = projectServiceFacade.findById(id);
		if (response.isSuccess() && response.getEntity() != null) {
			map.put("project", response.getEntity());
			// 查询图片
			ProjectImgDto projectImgDto = new ProjectImgDto();
			projectImgDto.setProjectId(id);
			projectImgDto.setDelFlag("0");
			ResponseList<ProjectImg> responseListImg = projectImgServiceFacade.findByDto(projectImgDto);
			if (responseListImg.isSuccess() && null != responseListImg.getEntity()) {
				map.put("imgList", responseListImg.getEntity());
			}

			ProjectInfoDto projectInfoDto = new ProjectInfoDto();
			projectInfoDto.setProjectId(id);
			ResponseList<ProjectInfo> responseProjectInfo = projectInfoServiceFacade.findByDto(projectInfoDto);
			if (responseProjectInfo.isSuccess() && null != responseProjectInfo.getEntity()
					&& responseProjectInfo.getEntity().size() > 0) {
				map.put("projectInfo", responseProjectInfo.getEntity().get(0));
			}

			ProjectSettingDto projectSettingDto = new ProjectSettingDto();
			projectSettingDto.setProjectId(id);
			ResponseList<ProjectSetting> setResponseList = projectSettingServiceFacade.findByDto(projectSettingDto);
			if (setResponseList.isSuccess() && null != setResponseList.getEntity()
					&& setResponseList.getEntity().size() > 0) {
				map.put("projectSetting", setResponseList.getEntity().get(0));
			} else {
				map.put("projectSetting", new ProjectSetting());
			}

			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			if (pmoResponse.isSuccess() && null != pmoResponse.getEntity() && pmoResponse.getEntity().size() > 0) {
				map.put("projectPmo", pmoResponse.getEntity().get(0));
			}
			String promotName = null;
			ProjectPmoDto ppDto = new ProjectPmoDto();
			ppDto.setProjectId(id);
			ResponseList<ProjectPmo> resList = projectPmoServiceFacade.findByDto(ppDto);
			if (resList.isSuccess()) {
				List<ProjectPmo> ppList = resList.getEntity();
				if (null != ppList) {
					ProjectPmo pp = ppList.get(0);
					promotName = pp.getPromotName();
				}
			}
			map.put("promotName", promotName);
		}
		return "/estate/project/form";
	}

	/**
	 * 方法描述 : 跳转修改页面 创建者：ThinkPad 项目名称： emm-website 类名： ProjectController.java 版本：
	 * v1.0 创建时间： 2016年5月31日 下午2:57:58
	 * 
	 * @return ModelAndView
	 */

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(ProjectVo projectVo, ProjectInfoVo projectInfoVo, ProjectSettingVo projectSettingVo,
			ProjectPmo projectPmo, Long projectInfoId, Long settingId, Long pmoId, Long imgId, String otherProjectType,
			SaleReturnPmoVo srpVo) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		// 总经理
		if (null == projectSettingVo.getGeneralManager()) {
			projectSettingVo.setGeneralManager(null);
		}
		// 项目总
		if (null == projectSettingVo.getProjectLeader()) {
			projectSettingVo.setProjectLeader(null);
		}
		// 经济总
		if (null == projectSettingVo.getSaleLeader()) {
			projectSettingVo.setSaleLeader(null);
		}

		// 销售经理
		if (null == projectSettingVo.getFieldLeader()) {
			projectSettingVo.setFieldLeader(null);
		}

		// 财务经理
		if (null == projectSettingVo.getFinanceLeader()) {
			projectSettingVo.setFinanceLeader(null);
		}
		// 销管经理
		if (null == projectSettingVo.getMaLeader()) {
			projectSettingVo.setMaLeader(null);
		}
		// 区域领导
		if (null == projectSettingVo.getAreaLeader()) {
			projectSettingVo.setAreaLeader(null);
		}
		// 区域经理
		if (null == projectSettingVo.getAreaManager()) {
			projectSettingVo.setAreaManager(null);
		}
		String authStr = "estate:project:add";
		if (null != projectInfoId) {
			authStr = "estate:project:edit";
		}
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, authStr))) {
			try {
				projectInfoVo.setId(projectInfoId);
				projectSettingVo.setId(settingId);
				User user = ShiroUtil.getCurrentUser();
				if (StringUtils.isNotBlank(otherProjectType)) {
					// 将其它产品类型存到remark字段中，避免新加字段
					projectVo.setRemark(otherProjectType);
				}
				projectVo.setMerchantId(user.getMerchantId());
				projectVo.setUserCode(user.getUserCode());
				projectVo.setCreateUserId(user.getId());
				projectVo.setDelFlag("0");
				projectVo.setUpdateUserId(user.getId());
				projectVo.setUpdateTime(new Date());

				projectInfoVo.setMerchantId(user.getMerchantId());
				projectInfoVo.setUserCode(user.getUserCode());
				projectInfoVo.setCreateUserId(user.getId());
				projectInfoVo.setDelFlag("0");
				projectInfoVo.setUpdateUserId(user.getId());
				projectInfoVo.setUpdateTime(new Date());

				projectSettingVo.setMerchantId(user.getMerchantId());
				projectSettingVo.setUserCode(user.getUserCode());
				projectSettingVo.setCreateUserId(user.getId());
				projectSettingVo.setDelFlag("0");
				projectSettingVo.setUpdateUserId(user.getId());
				projectSettingVo.setUpdateTime(new Date());

				// pmo信息
				projectPmo.setId(pmoId);
				projectPmo.setMerchantId(user.getMerchantId());
				projectPmo.setDelFlag("0");
				projectPmo.setUpdateTime(new Date());

				Validator validator = new Validator();
				List<ConstraintViolation> projectVoError = validator.validate(projectVo);
				List<ConstraintViolation> projectInfoVoError = validator.validate(projectInfoVo);
				List<ConstraintViolation> projectSettingError = validator.validate(projectSettingVo);
				if (projectVoError != null && projectVoError.size() > 0) {
					ar.setFailMsg(projectVoError.get(0).getMessage());
					return ar;
				}
				if (projectInfoVoError != null && projectInfoVoError.size() > 0) {
					ar.setFailMsg(projectInfoVoError.get(0).getMessage());
					return ar;
				}
				if (projectSettingError != null && projectSettingError.size() > 0) {
					ar.setFailMsg(projectSettingError.get(0).getMessage());
					return ar;
				}

				ProjectDto projectDto = BeanUtil.convert2T(new ProjectDto(), projectVo);
				ProjectInfoDto projectInfoDto = BeanUtil.convert2T(new ProjectInfoDto(), projectInfoVo);
				ProjectSettingDto projectSettingDto = BeanUtil.convert2T(new ProjectSettingDto(), projectSettingVo);

				ProjectPmoDto projectPmoDto = BeanUtil.convert2T(new ProjectPmoDto(), projectPmo);
				// 保存项目信息
				Response<ProjectDto> response = projectServiceFacade.save(projectDto, projectInfoDto, projectSettingDto,
						projectPmoDto);
				if (!response.isSuccess()) {
					ar.setFailMsg(response.getResultMessage());
					return ar;
				}
				// 保存图片
				saveProjectImg(user, response.getEntity(), projectVo);

				// 新增销售组
				projectSettingDto.setProjectCode(response.getEntity().getProjectCode());
				projectSettingDto.setProjectId(response.getEntity().getId());
				initSalesGroup(user, projectSettingDto);
				// 初始化流程
				initProcessDef(response.getEntity().getId(), response.getEntity().getProjectCode(), user);

				// 动态货值偏差原因
				String srpDynamic = srpVo.getSrpDynamic();
				com.alibaba.fastjson.JSONArray srpDynamicArray = com.alibaba.fastjson.JSONArray.parseArray(srpDynamic);
				if (null != srpDynamicArray) {
					for (int ii = 0; ii < srpDynamicArray.size(); ii++) {
						com.alibaba.fastjson.JSONObject srpDynamicObj = srpDynamicArray.getJSONObject(ii);
						String id = srpDynamicObj.getString("dynamicInfoId");
						String saleYear = srpDynamicObj.getString("saleYear");
						String saleMonth = srpDynamicObj.getString("saleMonth");
						String salePlan = srpDynamicObj.getString("salePlan");
						String saleActual = srpDynamicObj.getString("saleActual");
						String saleDiff = srpDynamicObj.getString("saleDiff");
						String saleDiffReason = srpDynamicObj.getString("saleDiffReason");
						if (StringUtils.isNotEmpty(id)) {
							SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
							srpDto.setId(Long.parseLong(id));
							srpDto.setSalePlan(salePlan);
							srpDto.setSaleActual(saleActual);
							srpDto.setSaleDiff(saleDiff);
							srpDto.setSaleDiffReason(saleDiffReason);
							saleReturnPmoServiceFacade.updateByPrimaryKey(srpDto, true);
						} else {
							SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
							srpDto.setSaleReturn(SaleReturnEnum.DYNAMIC.getNo());
							srpDto.setObjectType(ObjectTypeEnum.PROJECT.getNo());
							srpDto.setObjectId(projectDto.getId());
							srpDto.setSaleYear(saleYear);
							srpDto.setSaleMonth(saleMonth);
							srpDto.setSalePlan(salePlan);
							srpDto.setSaleActual(saleActual);
							srpDto.setSaleDiff(saleDiff);
							srpDto.setSaleDiffReason(saleDiffReason);
							srpDto.setCreateUserId(user.getId());
							srpDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							saleReturnPmoServiceFacade.save(srpDto);
						}
					}
				}

				// 更新项目名称和房间表中的combined_name
				Response<Boolean> res = projectServiceFacade.updateProjectAndRoom(projectDto, projectPmoDto);
				if (!res.isSuccess()) {
					logger.error("更新项目名称和房间表中的combined_name失败");
				}
				//20190114 jzliu 增加推送条件，只有绿城项目才进行推送
				if(user.getMerchantId() == 1) {
					// 推送静态数据
					levelStaticSalesDataService.updateProjectInfo(user.getMerchantId(), response.getEntity().getId());
				}

				ar.setSucceedMsg(projectVo.getId() == null ? Const.SAVE_SUCCEED : Const.UPDATE_SUCCEED);
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(e.getMessage());
			}
		}
		return ar;
	}

	private void initProcessDef(Long projectId, String projectCode, User user) {
		try {
			// 商户自定义流程前缀
			String procDefinedPrefix = getProcDefinedPrefix(user);
			for (ProcessTypeEnums pte : ProcessTypeEnums.values()) {
				ProjectProcdefDto ppdQuery = new ProjectProcdefDto();
				ppdQuery.setMerchantId(user.getMerchantId());
				ppdQuery.setProjectId(projectId);
				ppdQuery.setProcType(pte.getNo());
				ResponseList<ProjectProcdef> ppList = projectProcdefServiceFacade.findByDto(ppdQuery);
				if (ppList.isSuccess() && null != ppList.getEntity() && ppList.getEntity().size() > 0) {
					continue;
				}
				// 查询流程,获取前缀信息
				String pteNo = pte.getNo();
				String pteInit = pte.getInit();

				// 过滤掉1类型的枚举值
				if (!"0".equals(pteInit)) {
					continue;
				}
				// 新的流程类型
				String newPteKey = "";
				// 新流程类型对应的流程key
				// 由于流程Key可能与原定义key不一致(主要原因为定义的字段太长了,不得不改),名字给修改过.
				// 需重新获取一遍.
				String newPteNo = pteNo;
				if (StringUtils.isNotEmpty(procDefinedPrefix)) {
					newPteKey = procDefinedPrefix + pteNo;
					ProcessTypeEnums ptEnums = ProcessTypeEnums.getByNo(newPteKey);
					if (null == ptEnums) {
						continue;
					}
					newPteNo = ptEnums.getDes();
				}
				ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
				List<ProcessDefinition> processDefinitionList = query.processDefinitionKey(newPteNo).list();
				if (null == processDefinitionList || processDefinitionList.size() == 0) {
					continue;
				}
				ProjectProcdefDto ppd = new ProjectProcdefDto();
				ppd.setMerchantId(user.getMerchantId());
				ppd.setUserCode(user.getUserCode());
				ppd.setProjectId(projectId);
				ppd.setAccessCode(projectCode);
				ppd.setCreateUserId(user.getId());
				ppd.setUpdateTime(new Date());
				ppd.setDelFlag("0");
				ProcessDefinition processDefinition = processDefinitionList.get(0);
				ppd.setProcKey(processDefinition.getKey());
				ppd.setProcdefId(processDefinition.getId());
				ppd.setProcName(processDefinition.getName());
				ppd.setProcType(pte.getNo());
				projectProcdefServiceFacade.save(ppd);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}

	}

	private void initSalesGroup(User user, ProjectSettingDto projectSettingDto) throws Exception {
		// 组装销售组
		SalesGroupDto dto = new SalesGroupDto();
		dto.setProjectId(projectSettingDto.getProjectId());
		dto.setProjectCode(projectSettingDto.getProjectCode());
		dto.setName("管理组");
		dto.setSort(0);
		dto.setStatus("0");
		dto.setSaleAttr("1");
		dto.setRemark("新建项目,初始化管理组");
		dto.setOriginal("project");
		// 组装销售组成员
		List<SalesGroupUserDto> userDto = new ArrayList<SalesGroupUserDto>();
		// 公司总经理
		SalesGroupUserDto sgu0 = new SalesGroupUserDto();
		sgu0.setUserId(projectSettingDto.getGeneralManager());
		sgu0.setStatus("0");
		sgu0.setRemark("新建项目,初始化管理组公司总经理");
		// 项目负责人
		SalesGroupUserDto sgu1 = new SalesGroupUserDto();
		sgu1.setUserId(projectSettingDto.getProjectLeader());
		sgu1.setStatus("0");
		sgu1.setRemark("新建项目,初始化管理组项目负责人");
		// 营销负责人
		SalesGroupUserDto sgu2 = new SalesGroupUserDto();
		sgu2.setUserId(projectSettingDto.getSaleLeader());
		sgu2.setStatus("0");
		sgu2.setRemark("新建项目,初始化管理组营销负责人");

		// 案场负责人
		SalesGroupUserDto sgu3 = new SalesGroupUserDto();
		sgu3.setUserId(projectSettingDto.getFieldLeader());
		sgu3.setStatus("0");
		sgu3.setRemark("新建项目,初始化管理组案场负责人");

		// 财务负责人
		SalesGroupUserDto sgu4 = new SalesGroupUserDto();
		sgu4.setUserId(projectSettingDto.getFinanceLeader());
		sgu4.setStatus("0");
		sgu4.setRemark("新建项目,初始化管理组财务负责人");
		// 销管负责人
		SalesGroupUserDto sgu5 = new SalesGroupUserDto();
		sgu5.setUserId(projectSettingDto.getMaLeader());
		sgu5.setStatus("0");
		sgu5.setRemark("新建项目,初始化管理组销管负责人");
		// 区域负责人
		SalesGroupUserDto sgu6 = new SalesGroupUserDto();
		sgu6.setUserId(projectSettingDto.getAreaLeader());
		sgu6.setStatus("0");
		sgu6.setRemark("新建项目,初始化管理组区域负责人");

		SalesGroupUserDto sgu7 = new SalesGroupUserDto();
		sgu7.setUserId(projectSettingDto.getAreaManager());
		sgu7.setStatus("0");
		sgu7.setRemark("新建项目,初始化管理组区域负责人");

		if (isAdd(userDto, sgu0))
			userDto.add(sgu0);
		if (isAdd(userDto, sgu1))
			userDto.add(sgu1);
		if (isAdd(userDto, sgu2))
			userDto.add(sgu2);
		if (isAdd(userDto, sgu3))
			userDto.add(sgu3);
		if (isAdd(userDto, sgu4))
			userDto.add(sgu4);
		if (isAdd(userDto, sgu5))
			userDto.add(sgu5);
		if (isAdd(userDto, sgu6))
			userDto.add(sgu6);
		if (isAdd(userDto, sgu7))
			userDto.add(sgu7);
		Response<Integer> response = salesGroupUserServiceFacade.batchGroupUser(user, dto, userDto);
		if (!response.isSuccess()) {
			throw new RuntimeException(response.getResultMessage());
		}

	}

	private boolean isAdd(List<SalesGroupUserDto> userDto, SalesGroupUserDto salesGroupUserDto) {
		if (salesGroupUserDto.getUserId() == null)
			return false;
		for (SalesGroupUserDto sgud : userDto) {
			if (sgud.getUserId().compareTo(salesGroupUserDto.getUserId()) == 0) {
				return false;
			}
		}
		return true;
	}

	private void saveProjectImg(User user, ProjectDto projectDto, ProjectVo projectVo) {
		if (null == projectDto)
			return;
		if (null == projectVo)
			return;
		// 删除这个项目下面所有的图片
		if (projectDto.getId() != null) {
			ProjectImgDto dto = new ProjectImgDto();
			dto.setProjectId(projectDto.getId());
			dto.setProjectImgCode("projectCode");
			ResponseList<ProjectImg> list = projectImgServiceFacade.findByDto(dto);
			if (list.isSuccess() && list.getEntity() != null) {
				for (ProjectImg img : list.getEntity()) {
					projectImgServiceFacade.deleteByPrimaryKey(img.getId());
				}
			}
		}
		Long projectId = projectDto.getId();
		String projectCode = projectDto.getProjectCode();
		// 项目logo
		saveImg(user, projectId, projectCode, projectVo.getLogoUrl(), "1");
		// 总平面图
		saveImg(user, projectId, projectCode, projectVo.getPlaneUrl(), "2");
		// 周边配套图
		saveImg(user, projectId, projectCode, projectVo.getPeripheryUrl(), "3");
		// 交通图
		saveImg(user, projectId, projectCode, projectVo.getTrafficUrl(), "4");
		// 实景图
		saveImg(user, projectId, projectCode, projectVo.getRealUrl(), "5");
		// 样板图
		saveImg(user, projectId, projectCode, projectVo.getModelUrl(), "6");
		// 效果图
		saveImg(user, projectId, projectCode, projectVo.getEffectUrl(), "7");
	}

	private void saveImg(User user, Long projectId, String projectCode, String imgUrl, String type) {
		if (StringUtils.isBlank(imgUrl))
			return;
		String[] urls = imgUrl.split(";");
		if (null == urls || urls.length <= 0)
			return;
		for (int i = 0; i < urls.length; i++) {
			ProjectImgDto projectImgDto = new ProjectImgDto();
			projectImgDto.setUserCode(user.getUserCode());
			projectImgDto.setMerchantId(user.getMerchantId());
			projectImgDto.setDelFlag("0");
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setLargeUrl(urls[i]);
			projectImgDto.setNormalUrl(urls[i]);
			projectImgDto.setSmallUrl(urls[i]);
			projectImgDto.setProjectImgType(type);
			projectImgDto.setProjectCode(projectCode);
			projectImgDto.setAccessCode(projectCode);
			projectImgDto.setProjectId(projectId);
			projectImgDto.setCreateUserId(user.getId());
			projectImgDto.setProjectImgCode("projectCode");
			projectImgServiceFacade.save(projectImgDto);
		}

	}

	// 查看
	@RequestMapping(value = "detail")
	@MerchantResourcesConfig(resourcesCode = "menu_0003_0001_0004")
	public String detail(ModelMap map, Long id, HttpServletRequest request, HttpServletResponse httpServletResponse) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:view")) {
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("menu", request.getParameter("menu"));
			try {
				// 查询项目基本信息
				Response<Project> response = projectServiceFacade.findById(id);
				if (response.isSuccess()) {
					map.put("project", response.getEntity());
					// 产品类型名称
					String projectType = response.getEntity().getProjectType();
					if (StringUtils.isNotBlank(projectType)) {
						String[] pt = projectType.split(",");
						String projectTypeEnumName = "";
						for (String pte : pt) {
							if (!projectTypeEnumName.equals("")) {
								projectTypeEnumName = projectTypeEnumName + ",";
							}
							projectTypeEnumName = projectTypeEnumName + ProjectTypeEnum.getByNo(pte).getDes();
						}
						map.put("projectTypeName", projectTypeEnumName);
					} else {
						map.put("projectTypeName", "");
					}
					// 项目类型名称
					String itemType = response.getEntity().getItemType();
					if (StringUtils.isNotBlank(itemType)) {
						map.put("itemTypeName", ItemTypesEnum.getByNo(itemType).getDes());
					} else {
						map.put("itemTypeName", "");
					}

				} else {
					map.put("project", new Project());
					map.put("projectTypeName", "");
				}
				ProjectInfoDto projectInfoDto = new ProjectInfoDto();
				projectInfoDto.setProjectId(id);
				ResponseList<ProjectInfo> responseList = projectInfoServiceFacade.findByDto(projectInfoDto);
				if (responseList.isSuccess() && null != responseList.getEntity()
						&& responseList.getEntity().size() > 0) {
					map.put("projectInfo", responseList.getEntity().get(0));
				} else {
					map.put("projectInfo", new ProjectInfo());
				}
				ProjectSettingDto projectSettingDto = new ProjectSettingDto();
				projectSettingDto.setProjectId(id);
				ResponseList<ProjectSetting> setResponseList = projectSettingServiceFacade.findByDto(projectSettingDto);
				if (setResponseList.isSuccess() && null != setResponseList.getEntity()
						&& setResponseList.getEntity().size() > 0) {
					ProjectSetting projectSetting = setResponseList.getEntity().get(0);
					map.put("projectSetting", projectSetting);
					// 公司总经理
					map.put("generalManager", getUserById(projectSetting.getGeneralManager()));
					// 项目总
					map.put("projectLeader", getUserById(projectSetting.getProjectLeader()));
					// 经纪总
					map.put("saleLeader", getUserById(projectSetting.getSaleLeader()));
					// 销售经理
					map.put("fieldLeader", getUserById(projectSetting.getFieldLeader()));
					// 财务经理
					map.put("financeLeader", getUserById(projectSetting.getFinanceLeader()));
					// 销管经理
					map.put("maLeader", getUserById(projectSetting.getMaLeader()));
					// 区域领导
					map.put("areaLeader", getUserById(projectSetting.getAreaLeader()));
					// 区域经理
					map.put("areaManager", getUserById(projectSetting.getAreaManager()));

				} else {
					map.put("projectSetting", new ProjectSetting());
					// 公司总经理
					map.put("generalManager", new User());
					// 项目总
					map.put("projectLeader", new User());
					// 经纪总
					map.put("saleLeader", new User());
					// 销售经理
					map.put("fieldLeader", new User());
					// 财务经理
					map.put("financeLeader", new User());
					// 销管经理
					map.put("maLeader", new User());
					// 区域领导
					map.put("areaLeader", new User());
					// 区域经理
					map.put("areaManager", new User());
				}
				// 查询城市
				Long areaId = response.getEntity().getAreaId();
				if (null == areaId || areaId == -1)
					areaId = response.getEntity().getCityId();
				Response<Area> responseArea = areaServiceFacade.findById(areaId);
				if (responseArea.isSuccess() && null != responseArea.getEntity()) {
					map.put("area", responseArea.getEntity());
				} else {
					map.put("area", new Area());
				}

				// 查询图片
				ProjectImgDto projectImgDto = new ProjectImgDto();
				projectImgDto.setProjectId(id);
				ResponseList<ProjectImg> responseListImg = projectImgServiceFacade.findByDto(projectImgDto);
				if (responseListImg.isSuccess() && null != responseListImg.getEntity()) {
					map.put("imgList", responseListImg.getEntity());
				} else {
					map.put("imgList", new ArrayList<ProjectImg>());
				}

			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return "/estate/projectBasic/newDetail";
	}

	// 查看
	@RequestMapping(value = "detailLC")
	public String detailLC(ModelMap map, Long id, HttpServletRequest request) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:view")) {
			map.addAttribute("id", id);
			return "/estate/project/detailLC";
		}
		return Const.NO_AUTHORIZED_URL;

	}

	private User getUserById(Long id) {
		if (null != id) {
			Response<User> response = userServiceFacade.findById(id);
			if (response.isSuccess()) {
				return response.getEntity();
			}
		}
		return new User();
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(ProjectDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:edit"))) {
			try {
				Response<Integer> response = projectServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:delete"))) {
			try {
				Response<Integer> response = projectServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	/**
	 * 变更PMO推送规则
	 * @param id
	 * @param pmoPush
	 * @return
	 */
	@RequestMapping(value = "setPmoPush", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes setPmoPush(Long id, String pmoPush) {
		AjaxRes ar = getAjaxRes();
		try {
			Response<Project> projectRes = projectServiceFacade.findById(id);
			if(projectRes.isSuccess() && null != projectRes.getEntity()){
				Project project = projectRes.getEntity();

				ProjectDto projectDto = new ProjectDto();
				projectDto.setId(project.getId());
				projectDto.setPmoPush(pmoPush);
				Response<Integer> response = projectServiceFacade.updateByPrimaryKey(projectDto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			}else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.UPDATE_FAIL);
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(ProjectListDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:list"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				// 用户权限字段
				dto.setPermissionUserId(user.getId());
				dto.setMerchantId(user.getMerchantId());
				dto.setColumnName("project_code");

				// 项目数据权限资源缓存
				String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
				if (null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())) {
					dto.setResourcesCode(resourcesCode);
				} else if ("".equals(resourcesCode)) {
					ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
				}

				if (dto.getProvinceId() != null && dto.getProvinceId().longValue() == Long.valueOf("-1").longValue())
					dto.setProvinceId(null);
				if (dto.getCityId() != null && dto.getCityId().longValue() == Long.valueOf("-1").longValue())
					dto.setCityId(null);
				dto.setUserId(user.getId());
				Page<ProjectList> response = projectServiceFacade.getProjectListPage(dto,
						PageUtil.begin(pageNum, pageSize), pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<ProjectList>());
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
					if (StringUtils.isNotEmpty(response.getErrorMsg())) {
						ar.setFailMsg(response.getErrorMsg());
					}
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	@ResponseBody
	@RequestMapping(value = "anthorizedList")
	public AjaxRes anthorizedList(ProjectDto dto, Long userId) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		dto.setMerchantId(user.getMerchantId());
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:project:anthorizedList"))) {
			ResponseList<com.emm.yixun.common.model.ZNodes> responseList = userProjectServiceFacade.anthorizedList(dto,
					userId);
			if (responseList.isSuccess()) {
				ar.setSucceed(responseList.getEntity());
			}
		}
		return ar;
	}

	@RequestMapping(value = "findProjectList")
	public @ResponseBody RootClass findProjectList(ProjectDto dto) {
		User user = ShiroUtil.getCurrentUser();
		dto.setDelFlag("0");
		dto.setPermissionUserId(user.getId());

		// 项目数据权限资源缓存

		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
		if (null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())) {
			dto.setResourcesCode(resourcesCode);
		} else if ("".equals(resourcesCode)) {
			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
		}
		dto.setMerchantId(user.getMerchantId());
		ResponseList<Project> projectList = projectServiceFacade.findByDto(dto);
		RootClass root = new RootClass();
		root.setRoot(projectList.getEntity());
		return root;
	}

	// 查询项目角色人员
	@RequestMapping(value = "findProjectRoleUser")
	@ResponseBody
	public AjaxRes findProjectRoleUser(Long projectId, String roleId) {
		AjaxRes ar = getAjaxRes();
		ProjectSettingDto projectSettingDto = new ProjectSettingDto();
		projectSettingDto.setProjectId(projectId);
		ResponseList<ProjectSetting> setResponseList = projectSettingServiceFacade.findByDto(projectSettingDto);
		if (!setResponseList.isSuccess() || null == setResponseList.getEntity()
				|| setResponseList.getEntity().size() == 0) {
			ar.setSucceed(new User());
			return ar;
		}
		ProjectSetting projectSetting = setResponseList.getEntity().get(0);
		User user = new User();
		if (roleId.equals(ProjectRoleEnums.VALUE_1.getNo())) {
			// 公司总经理
			user = getUserById(projectSetting.getGeneralManager());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_2.getNo())) {
			// 项目总
			user = getUserById(projectSetting.getProjectLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_3.getNo())) {
			// 经纪总
			user = getUserById(projectSetting.getSaleLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_4.getNo())) {
			// 销售经理
			user = getUserById(projectSetting.getFieldLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_5.getNo())) {
			// 销管经理
			user = getUserById(projectSetting.getMaLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_6.getNo())) {
			// 财务经理
			user = getUserById(projectSetting.getFinanceLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_7.getNo())) {
			// 区域领导
			user = getUserById(projectSetting.getAreaLeader());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_8.getNo())) {
			// 区域领导
			user = getUserById(projectSetting.getAreaManager());
			ar.setSucceed(user);
		} else if (roleId.equals(ProjectRoleEnums.VALUE_9.getNo())) {
			// 财务会计
			RoleDto role = new RoleDto();
			role.setRoleName("财务会计");
			ResponseList<Role> responseList =  roleServiceFacade.findByDto(role);
			if(responseList.isSuccess() && responseList.getEntity() != null && !responseList.getEntity().isEmpty()) {
				Role roles = responseList.getEntity().get(0);
				UserDto userDto = new UserDto();
				userDto.setRoleId(roles.getId());
				ResponseList<User> userlist = userServiceFacade.findByDto(userDto);
				ar.setSucceed(userlist.getEntity());
			}
		}
		
		return ar;
	}

	// 当projectProcessFlag==true时，初始化项目流程，否则不初始化项目流程
	@RequestMapping(value = "initProjectProcess")
	@ResponseBody
	public String initProjectProcess(Boolean projectProcessFlag) {
		if (null == projectProcessFlag) {
			projectProcessFlag = false;
		}
		StringBuffer sb = new StringBuffer();
		try {
			ResponseList<Merchant> merchantList = merchantServiceFacade.findByDto(new MerchantDto());
			if (!merchantList.isSuccess() || null == merchantList.getEntity() || merchantList.getEntity().size() == 0) {
				return "未查询到商户信息";
			}
			sb.append("商户：");
			for (Merchant m : merchantList.getEntity()) {
				initMerchantProjectProcess(m.getId(), projectProcessFlag);
				sb.append(m.getMerchantName());
				sb.append(";");
			}
			sb.append("项目流程初始化成功！");
		} catch (Exception e) {
			sb.append("项目流程初始化错误！");
		}
		return sb.toString();
	}

	private void initMerchantProjectProcess(Long merchantId, Boolean projectProcessFlag) {
		// 查询当前商户管理员
		UserDto queryUd = new UserDto();
		queryUd.setMerchantId(merchantId);
		queryUd.setIsAdmin("1");
		ResponseList<User> userList = userServiceFacade.findByDto(queryUd);
		User adminUser = userList.getEntity().get(0);

		List<MearchantProcdefDto> mearchantProcdefList = new ArrayList<MearchantProcdefDto>();

		// 商户自定义流程前缀
		String procDefinedPrefix = getProcDefinedPrefix(adminUser);

		// 初始化商户流程
		for (ProcessTypeEnums pte : ProcessTypeEnums.values()) {

			// 查询流程,获取前缀信息
			String pteNo = pte.getNo();
			String pteInit = pte.getInit();

			// petInit为定制化流程
			if (!"0".equals(pteInit)) {
				continue;
			}
			// 新的流程类型
			String newPteKey = "";
			// 新流程类型对应的流程key
			// 由于流程Key可能与原定义key不一致(主要原因为定义的字段太长了,不得不改),名字给修改过.
			// 需重新获取一遍.
			String newPteNo = pteNo;
			if (StringUtils.isNotEmpty(procDefinedPrefix)) {
				newPteKey = procDefinedPrefix + pteNo;
				ProcessTypeEnums ptEnums = ProcessTypeEnums.getByNo(newPteKey);
				if (null == ptEnums) {
					continue;
				}
				newPteNo = ptEnums.getDes();
			}

			ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
			List<ProcessDefinition> processDefinitionList = query.processDefinitionKey(newPteNo).list();
			if (null == processDefinitionList || processDefinitionList.size() == 0) {
				continue;
			}
			ProcessDefinition processDefinition = processDefinitionList.get(0);
			MearchantProcdefDto mpd = new MearchantProcdefDto();
			mpd.setMerchantId(merchantId);
			mpd.setCreateUserId(adminUser.getId());
			mpd.setUpdateTime(new Date());
			mpd.setDelFlag("0");
			mpd.setProcKey(processDefinition.getKey());
			mpd.setProcdefId(processDefinition.getId());
			mpd.setProcName(processDefinition.getName());
			mpd.setProcType(pte.getNo());
			mearchantProcdefServiceFacade.save(mpd);
			mearchantProcdefList.add(mpd);
		}
		if (!projectProcessFlag)
			return;
		// 查询当前商户项目
		ProjectDto queryProjectDto = new ProjectDto();
		queryProjectDto.setMerchantId(merchantId);
		ResponseList<Project> projectListResponse = projectServiceFacade.findByDto(queryProjectDto);
		if (!projectListResponse.isSuccess() || null == projectListResponse.getEntity()
				|| projectListResponse.getEntity().size() == 0) {
			return;
		}
		// 初始化商户项目流程
		for (Project project : projectListResponse.getEntity()) {
			for (MearchantProcdefDto mdd : mearchantProcdefList) {
				ProjectProcdefDto ppd = new ProjectProcdefDto();
				ppd.setUserCode(adminUser.getUserCode());
				ppd.setProjectId(project.getId());
				ppd.setAccessCode(project.getProjectCode());
				ppd.setCreateUserId(adminUser.getId());
				ppd.setUpdateTime(new Date());
				ppd.setDelFlag("0");
				ppd.setMerchantId(merchantId);
				ppd.setProcKey(mdd.getProcKey());
				ppd.setProcdefId(mdd.getProcdefId());
				ppd.setProcName(mdd.getProcName());
				ppd.setProcType(mdd.getProcType());
				projectProcdefServiceFacade.save(ppd);
			}
		}

	}

	@RequestMapping(value = "addMerchantProcess")
	@ResponseBody
	public String addMerchantProcess(Long merchantId, String processDefinitionKey) {
		// 查询商户管理员
		UserDto queryUd = new UserDto();
		queryUd.setMerchantId(merchantId);
		queryUd.setIsAdmin("1");
		ResponseList<User> userList = userServiceFacade.findByDto(queryUd);
		User adminUser = userList.getEntity().get(0);
		// 查询商户项目
		ProjectDto queryProjectDto = new ProjectDto();
		queryProjectDto.setMerchantId(merchantId);
		ResponseList<Project> projectListResponse = projectServiceFacade.findByDto(queryProjectDto);
		if (!projectListResponse.isSuccess() || null == projectListResponse.getEntity()
				|| projectListResponse.getEntity().size() == 0) {
			return "error";
		}
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		List<ProcessDefinition> processDefinitionList = query.processDefinitionKey(processDefinitionKey).list();
		if (null == processDefinitionList || processDefinitionList.size() == 0) {
			return "error";
		}
		for (Project project : projectListResponse.getEntity()) {
			ProjectProcdefDto ppd = new ProjectProcdefDto();
			ppd.setMerchantId(merchantId);
			ppd.setUserCode(adminUser.getUserCode());
			ppd.setProjectId(project.getId());
			ppd.setAccessCode(project.getProjectCode());
			ppd.setCreateUserId(adminUser.getId());
			ppd.setUpdateTime(new Date());
			ppd.setDelFlag("0");
			ProcessDefinition processDefinition = processDefinitionList.get(0);
			ppd.setProcKey(processDefinition.getKey());
			ppd.setProcdefId(processDefinition.getId());
			ppd.setProcName(processDefinition.getName());
			ppd.setProcType(ProcessTypeEnums.getByNo(processDefinitionKey).getNo());
			projectProcdefServiceFacade.save(ppd);
		}
		return "success:" + projectListResponse.getEntity().size();
	}

	@RequestMapping(value = "sendStaticSalePmo")
	@ResponseBody
	public Response<?> sendStaticSalePmo(Long projectId) {
		User user = ShiroUtil.getCurrentUser();
		Response<?> response = new Response<Object>();
		try {
			if (user.getMerchantId() == 1) {
				response = levelStaticSalesDataService.updateProjectInfo(user.getMerchantId(), projectId);
			} else {
				response.setSuccess(false);
				response.setErrorCode("9999");
				response.setResultMessage("该商家不能进行推送");
			}
		} catch (Exception e) {
			logger.error("SendStaticSalePmo error===", e);
			response.setSuccess(false);
			response.setErrorCode("9999");
			response.setResultMessage("推送静态销售主数据失败");
		}
		return response;
	}

	@RequestMapping(value = "testSendDynamiPmo")
	@ResponseBody
	public String testSendDynamiPmo(String pmoProjectCode, String month) {

		try {
			levelProjectDataService.sendLevelProjectData(pmoProjectCode, month, false);
			return "success";
		} catch (Exception e) {
			return e.getMessage();
		}
	}

	@RequestMapping(value = "toProjectInfo")
	public String toProjectInfo(ModelMap map, HttpServletRequest request, Long id, HttpServletResponse response) {
		map.put("id", id);
		Map<String, Object> maps = loadProjectInfo(request, response, id);
		map.put("loadProjectInfo", maps);

		return "/estate/project/projectInfo";
	}

	/**
	 * 加載項目信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	public Map<String, Object> loadProjectInfo(HttpServletRequest request, HttpServletResponse response, Long id) {
		Map<String, Object> renturnMap = new HashMap<String, Object>();
		try {
			// 查询项目基本信息
			Response<Project> resPro = projectServiceFacade.findById(id);
			if (resPro.isSuccess()) {
				Project project = resPro.getEntity();
				if (project != null) {
					ProjectPremisesDto queryPremises = new ProjectPremisesDto();
					queryPremises.setProjectId(id);
					queryPremises.setDelFlag(DelFlagEnum.UNDEL.getNo());
					ResponseList<ProjectPremises> responseList = premisesServiceFacade.findByDto(queryPremises);
					if (responseList != null && responseList.getEntity() != null
							&& responseList.getEntity().size() > 0) {
						project.setStagesNum(responseList.getEntity().size());
					}
				}
				renturnMap.put("project", project);
				// 产品类型名称
				String projectType = resPro.getEntity().getProjectType();
				if (StringUtils.isNotBlank(projectType)) {
					String[] pt = projectType.split(",");
					String projectTypeEnumName = "";
					for (String pte : pt) {
						if (!projectTypeEnumName.equals("")) {
							projectTypeEnumName = projectTypeEnumName + ",";
						}
						projectTypeEnumName = projectTypeEnumName + ProjectTypeEnum.getByNo(pte).getDes();
					}
					renturnMap.put("projectTypeName", projectTypeEnumName);
				} else {
					renturnMap.put("projectTypeName", "");
				}
				// 项目类型名称
				String itemType = resPro.getEntity().getItemType();
				if (StringUtils.isNotBlank(itemType)) {
					renturnMap.put("itemTypeName", ItemTypesEnum.getByNo(itemType).getDes());
				} else {
					renturnMap.put("itemTypeName", "");
				}
			} else {
				renturnMap.put("project", new Project());
				renturnMap.put("projectTypeName", "");
			}
			ProjectInfoDto projectInfoDto = new ProjectInfoDto();
			projectInfoDto.setProjectId(id);
			ResponseList<ProjectInfo> responseList = projectInfoServiceFacade.findByDto(projectInfoDto);
			if (responseList.isSuccess() && null != responseList.getEntity() && responseList.getEntity().size() > 0) {
				renturnMap.put("projectInfo", responseList.getEntity().get(0));
			} else {
				renturnMap.put("projectInfo", new ProjectInfo());
			}
			// 项目设置
			ProjectSettingDto projectSettingDto = new ProjectSettingDto();
			projectSettingDto.setProjectId(id);
			ResponseList<ProjectSetting> setResponseList = projectSettingServiceFacade.findByDto(projectSettingDto);
			if (setResponseList.isSuccess() && null != setResponseList.getEntity()
					&& setResponseList.getEntity().size() > 0) {
				ProjectSetting projectSetting = setResponseList.getEntity().get(0);
				renturnMap.put("projectSetting", projectSetting);
				// 公司总经理
				renturnMap.put("generalManager", getUserById(projectSetting.getGeneralManager()));
				// 项目总
				renturnMap.put("projectLeader", getUserById(projectSetting.getProjectLeader()));
				// 经纪总
				renturnMap.put("saleLeader", getUserById(projectSetting.getSaleLeader()));
				// 销售经理
				renturnMap.put("fieldLeader", getUserById(projectSetting.getFieldLeader()));
				// 财务经理
				renturnMap.put("financeLeader", getUserById(projectSetting.getFinanceLeader()));
				// 销管经理
				renturnMap.put("maLeader", getUserById(projectSetting.getMaLeader()));
				// 区域领导
				renturnMap.put("areaLeader", getUserById(projectSetting.getAreaLeader()));
				// 区域经理
				renturnMap.put("areaManager", getUserById(projectSetting.getAreaManager()));
			} else {
				renturnMap.put("projectSetting", new ProjectSetting());
				// 公司总经理
				renturnMap.put("generalManager", new User());
				// 项目总
				renturnMap.put("projectLeader", new User());
				// 经纪总
				renturnMap.put("saleLeader", new User());
				// 销售经理
				renturnMap.put("fieldLeader", new User());
				// 财务经理
				renturnMap.put("financeLeader", new User());
				// 销管经理
				renturnMap.put("maLeader", new User());
				// 区域领导
				renturnMap.put("areaLeader", new User());
				// 区域经理
				renturnMap.put("areaManager", new User());
			}
			// 查询城市
			Long areaId = resPro.getEntity().getAreaId();
			if (null == areaId || areaId == -1)
				areaId = resPro.getEntity().getCityId();
			Response<Area> responseArea = areaServiceFacade.findById(areaId);
			if (responseArea.isSuccess() && null != responseArea.getEntity()) {
				renturnMap.put("area", responseArea.getEntity());
			} else {
				renturnMap.put("area", new Area());
			}

			// 查询图片
			ProjectImgDto projectImgDto = new ProjectImgDto();
			projectImgDto.setProjectId(id);
			ResponseList<ProjectImg> responseListImg = projectImgServiceFacade.findByDto(projectImgDto);
			if (responseListImg.isSuccess() && null != responseListImg.getEntity()) {
				renturnMap.put("imgList", responseListImg.getEntity());
			} else {
				renturnMap.put("imgList", new ArrayList<ProjectImg>());
			}
			// PMO相关信息
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			if (pmoResponse.isSuccess() && null != pmoResponse.getEntity() && pmoResponse.getEntity().size() > 0) {
				renturnMap.put("projectPmo", pmoResponse.getEntity().get(0));
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("加载绿城项目信息报错: ", ex);
		}
		return renturnMap;
	}

	/**
	 * 跳轉銷售情況頁面
	 * 
	 * @param map
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "toSaleView")
	public String toSaleView(ModelMap map, HttpServletRequest request, Long id) {
		map.put("id", id);
		return "/estate/project/saleView";
	}

	/**
	 * 加載銷售信息
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "loadSaleViewOld")
	public @ResponseBody Map<String, Object> loadSaleViewOld(HttpServletRequest request, HttpServletResponse response,
			Long id, String calYearMonth) {
		Map<String, Object> renturnMap = new HashMap<String, Object>();
		try {
			// 查询项目基本信息
			Project project = new Project();
			Response<Project> resPro = projectServiceFacade.findById(id);
			if (resPro.isSuccess()) {
				project = resPro.getEntity();
				renturnMap.put("project", project);
			} else {
				renturnMap.put("project", new Project());
				renturnMap.put("projectTypeName", "");
			}
			// PMO相关信息
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			ProjectPmo projectPmo = new ProjectPmo();
			if (pmoResponse.isSuccess() && null != pmoResponse.getEntity() && pmoResponse.getEntity().size() > 0) {
				projectPmo = pmoResponse.getEntity().get(0);
				renturnMap.put("projectPmo", projectPmo);
			}

			// 静态数据
			User user = ShiroUtil.getCurrentUser();
			//旧版功能实现 JHSong_2019-3-20
			Response<LevelStaticSalesData> levelList = levelStaticSalesDataServiceFacade.updateProjectInfo(user.getMerchantId(), id, false);
			//新版重构实现 JHSong_2019-3-20
			//Response<LevelStaticSalesData> levelList = pmoStaticDataServiceFacade.queryProjectStaticData(project, projectPmo, false);

			if (levelList.isSuccess() && levelList.getEntity() != null) {
				StaticSalesData staticSalesData = levelList.getEntity().getData();
				renturnMap.put("staticSalesData", staticSalesData);
			}

			// 动态数据
			if (StringUtils.isEmpty(calYearMonth)) {
				SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
				calYearMonth = sdf.format(Calendar.getInstance().getTime());
			}
			//旧版功能实现 JHSong_2019-3-20
			Response<LevelDynamiSalesData> dynamiResponse = projectServiceFacade.quereyLevelDynamiSalesData(pmoResponse.getEntity().get(0).getPmoProjectCode(), calYearMonth);

			//新版重构实现 JHSong_2019-3-20
			// 动态数据
			//if (StringUtils.isEmpty(calYearMonth)) {
			//	SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
			//	calYearMonth = sdf.format(Calendar.getInstance().getTime());
			//}
 			//Response<LevelDynamiSalesData> dynamiResponse = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(pmoResponse.getEntity().get(0).getPmoProjectCode(), calYearMonth);

			if (dynamiResponse.isSuccess() && dynamiResponse.getEntity() != null) {
				LevelDynamiSalesData levelDynamiSalesData = dynamiResponse.getEntity();
				renturnMap.put("levelDynamiSalesData", levelDynamiSalesData);
			}
			// 计划销售额，计划回款额
			renturnMap.putAll(querySaleReturn(id, null));
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("加载绿城项目信息报错: ", ex);
		}
		return renturnMap;
	}

	/**
	 * 銷售回款數據
	 * 供測試與銷售報表做數據核對，無實際作用。
	 * 使用方式： 直接在瀏覽器輸入地址，即可返回當月銷售及回款額
	 * id: 項目Id
	 * calYearMonth: 計算年月
	 * .....此處省略/emm-website/estate/project/loadSaleView?id=113&calYearMonth=201901
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "checkPmoSaleReturnData")
	public @ResponseBody Map<String, Object> checkPmoSaleReturnData(HttpServletRequest request, HttpServletResponse response,
														  Long id, String calYearMonth) {
		Map<String, Object> renturnMap = new HashMap<String, Object>();
		try {
			// PMO相关信息
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			ProjectPmo projectPmo = new ProjectPmo();
			if (pmoResponse.isSuccess() && null != pmoResponse.getEntity() && pmoResponse.getEntity().size() > 0) {
				projectPmo = pmoResponse.getEntity().get(0);
			}

			// 动态数据
			if (StringUtils.isEmpty(calYearMonth)) {
				SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
				calYearMonth = sdf.format(Calendar.getInstance().getTime());
			}
			Response<LevelDynamiSalesData> dynamiResponse = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(projectPmo.getPmoProjectCode(), calYearMonth);

			if (dynamiResponse.isSuccess() && dynamiResponse.getEntity() != null) {
				LevelDynamiSalesData levelDynamiSalesData = dynamiResponse.getEntity();
				renturnMap.put("銷售金額：", levelDynamiSalesData.getData().getActualSalesAmount());
				renturnMap.put("回款金額：", levelDynamiSalesData.getData().getActualBackAmount());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("加载绿城项目信息报错: ", ex);
		}
		return renturnMap;
	}

	/**
	 * 加載銷售信息
	 *
	 * @param request
	 * @param response
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "loadSaleView")
	public @ResponseBody Map<String, Object> loadSaleView(HttpServletRequest request, HttpServletResponse response,
														  Long id, String calYearMonth) {
		Map<String, Object> renturnMap = new HashMap<String, Object>();
		try {
			// 查询项目基本信息
			Project project = new Project();
			Response<Project> resPro = projectServiceFacade.findById(id);
			if (resPro.isSuccess()) {
				project = resPro.getEntity();
				renturnMap.put("project", project);
			} else {
				renturnMap.put("project", new Project());
				renturnMap.put("projectTypeName", "");
			}
			// PMO相关信息
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			ProjectPmo projectPmo = new ProjectPmo();
			if (pmoResponse.isSuccess() && null != pmoResponse.getEntity() && pmoResponse.getEntity().size() > 0) {
				projectPmo = pmoResponse.getEntity().get(0);
				renturnMap.put("projectPmo", projectPmo);
			}

			// 静态数据
			User user = ShiroUtil.getCurrentUser();
			//旧版功能实现 JHSong_2019-3-20
			//Response<LevelStaticSalesData> levelList = levelStaticSalesDataServiceFacade.updateProjectInfo(user.getMerchantId(), id, false);
			//新版重构实现 JHSong_2019-3-20
			Response<LevelStaticSalesData> levelList = pmoStaticDataServiceFacade.queryProjectStaticData(project, projectPmo, false);

			if (levelList.isSuccess() && levelList.getEntity() != null) {
				StaticSalesData staticSalesData = levelList.getEntity().getData();
				renturnMap.put("staticSalesData", staticSalesData);
			}

			// 动态数据
			//if (StringUtils.isEmpty(calYearMonth)) {
			//	SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
			//	calYearMonth = sdf.format(Calendar.getInstance().getTime());
			//}
			//旧版功能实现 JHSong_2019-3-20
			//Response<LevelDynamiSalesData> dynamiResponse = projectServiceFacade.quereyLevelDynamiSalesData(pmoResponse.getEntity().get(0).getPmoProjectCode(), calYearMonth);

			//新版重构实现 JHSong_2019-3-20
			// 动态数据
			if (StringUtils.isEmpty(calYearMonth)) {
				SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
				calYearMonth = sdf.format(Calendar.getInstance().getTime());
			}
			Response<LevelDynamiSalesData> dynamiResponse = pmoDynamicDataServiceFacade.quereyLevelDynamiSalesData(pmoResponse.getEntity().get(0).getPmoProjectCode(), calYearMonth);

			if (dynamiResponse.isSuccess() && dynamiResponse.getEntity() != null) {
				LevelDynamiSalesData levelDynamiSalesData = dynamiResponse.getEntity();
				renturnMap.put("levelDynamiSalesData", levelDynamiSalesData);
			}
			// 计划销售额，计划回款额
			renturnMap.putAll(querySaleReturn(id, null));
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("加载绿城项目信息报错: ", ex);
		}
		return renturnMap;
	}

	public Map<String, Object> querySaleReturn(Long id, Long premisesId) {
		Map<String, Object> renturnMap = new HashMap<String, Object>();
		try {
			// 销售计划
			ResponseList<SaleReturnPmo> responseSaleList = pmoDynamicDataServiceFacade.querySaleReturnListPmo(id, premisesId,
					SaleReturnEnum.SALE.getNo(), null);
			// 回款计划
			ResponseList<SaleReturnPmo> responseReturnList = pmoDynamicDataServiceFacade.querySaleReturnListPmo(id, premisesId,
					SaleReturnEnum.RETURN.getNo(), null);
			// 计划销售额
			renturnMap.put("srpSaleMap", responseSaleList.getEntity());
			// 计划回款额
			renturnMap.put("srpReturnMap", responseReturnList.getEntity());
		} catch (Exception ex) {
			logger.error("计划销售,回款额错误:", ex);
		}
		return renturnMap;
	}

	@RequestMapping(value = "toStageBrowse")
	public String toStageBrowse(ModelMap map, HttpServletRequest request, Long id, Long premisesId) {
		map.put("id", id);
		map.put("premisesId", premisesId);
		return "/estate/project/stageBrowse";
	}

	// 初始化项目流程
	@RequestMapping(value = "initProcessDef")
	public void initProcessDef(Long projectId, String projectCode) {
		initProcessDef(projectId, projectCode, ShiroUtil.getCurrentUser());
	}

	/**
	 * 获取流程自定义前缀
	 * 
	 * @param user
	 * @return
	 */
	public String getProcDefinedPrefix(User user) {
		String result = "";
		Response<Merchant> merchantResponse = merchantServiceFacade.findById(user.getMerchantId());
		if (merchantResponse.isSuccess() && merchantResponse.getEntity() != null) {
			String information = merchantResponse.getEntity().getPhoneInformation();
			com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
				String type = jsonObject.getString("type");
				String status = jsonObject.getString("status");
				if ("99".equals(type) && StringUtils.isNotEmpty(status)) {
					result = status;
				}
			}
		}
		return result;
	}

	@RequestMapping(value = "industPage")
	public ModelAndView industPage() {
		return new ModelAndView("/estate/project/industForm");
	}

	/**
	 * 
	 * createProjectIndust:项目新增业态. <br/>
	 * 
	 * @author Administrator
	 * @param premisesIndustDataDto
	 * @param projectId
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "createProjectIndust")
	public @ResponseBody AjaxRes createProjectIndust(ProjectPremisesIndustDataDto premisesIndustDataDto,
			Long projectId) {
		AjaxRes ar = getAjaxRes();
		try {
			HashMap<String, String> map = projectPremisesIndustDataService
					.createProjectIndustData(premisesIndustDataDto, projectId);
			// 推送PMO
			String pmoProjectCode = levelProjectDataService.getProjectPmoCode(projectId);
			levelProjectDataService.sendLevelProjectData(pmoProjectCode,
					DateUtils.formatDate(new Date(), DateStyle.YYYYMM.getValue()), true);
			if (map.get("error") == null) {
				ar.setSucceed(true);
				ar.setResMsg("保存成功");
			} else {
				ar.setSucceed(false);
				ar.setRes(Const.FAIL);
				ar.setResMsg(map.get("error"));
			}

		} catch (Exception e) {
			logger.error("保存失败: ", e);
			ar.setResMsg("保存失败");
			ar.setSucceed(false);
		}
		return ar;
	}

	/**
	 * 
	 * editSalesReturnPlant:编辑偏差原因 <br/>
	 *
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "editSalesReturnPlant")
	public @ResponseBody AjaxRes editSalesReturnPlant(Long id, String saleDiffReason) {
		AjaxRes ajaxRes = getAjaxRes();
		try {
			SaleReturnPmoDto dto = new SaleReturnPmoDto();
			dto.setId(id);
			dto.setSaleDiffReason(saleDiffReason);
			Response<Integer> response = saleReturnPmoServiceFacade.updateByPrimaryKey(dto, true);
			if (response.getEntity() > 0) {
				ajaxRes.setResMsg("保存成功");
			} else {
				ajaxRes.setResMsg("保存失败");
			}
		} catch (Exception e) {
			ajaxRes.setResMsg("保存失败");
			logger.error("保存失败: ", e);
		}
		return ajaxRes;
	}

	/**
	 * 
	 * projectPremisesData:项目下各个分期的静态,动态数据 <br/>
	 *
	 * @author Administrator
	 * @param id
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "projectPremisesData")
	public @ResponseBody List<LevelData> projectPremisesData(Long id, Long premisesId) {
		try {
			User user = ShiroUtil.getCurrentUser();
			// 项目下各分期的静态数据
			Response<LevelStaticSalesData> levelList = levelStaticSalesDataServiceFacade
					.updateProjectInfo(user.getMerchantId(), id, false);
			// 项目下各个分期的动态数据
			ProjectPmoDto projectPmoDto = new ProjectPmoDto();
			projectPmoDto.setProjectId(id);
			ResponseList<ProjectPmo> pmoResponse = projectPmoServiceFacade.findByDto(projectPmoDto);
			if (pmoResponse.isSuccess() && pmoResponse.getEntity() != null && pmoResponse.getEntity().size() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat(DateStyle.YYYYMM.getValue());
				String calYearMonth = sdf.format(Calendar.getInstance().getTime());
				Response<LevelDynamiSalesData> dynamiResponse = projectServiceFacade
						.quereyLevelDynamiSalesData(pmoResponse.getEntity().get(0).getPmoProjectCode(), calYearMonth);
				List<LevelData> map = assembleData(id, levelList.getEntity(), dynamiResponse.getEntity(), premisesId);
				return map;
			}

		} catch (Exception e) {
			logger.error("projectPremisesData error: ", e);
		}
		return null;
	}

	/**
	 * 
	 * assembleData:(项目级别 查询所有分期的业态，动态数据). <br/>
	 *
	 * 
	 * @author Administrator
	 * @param id
	 * @param premisesId
	 * @param levelStaticSalesData
	 * @param levelDynamiSalesData
	 * @return
	 * @since JDK 1.6
	 */
	public List<LevelData> assembleData(Long id, LevelStaticSalesData levelStaticSalesData,
			LevelDynamiSalesData levelDynamiSalesData, Long premisesId) {
		List<LevelData> levelDatas = new ArrayList<LevelData>();
		try {
			if (levelStaticSalesData != null && levelStaticSalesData.getStaticSalesDatas() != null) {
				for (int i = 0; i < levelStaticSalesData.getStaticSalesDatas().size(); i++) {

					LevelData data = new LevelData();
					LevelStaticSalesDataChild child = levelStaticSalesData.getStaticSalesDatas().get(i);
					if (premisesId != null && premisesId.compareTo(child.getPremisesId()) != 0) {
						continue;
					}

					data.setProjectName(child.getProjectName());
					Map<String, Object> maps = querySaleReturn(id, child.getPremisesId());
					if (maps.get("srpSaleMap") != null) {
						List<SaleReturnPmo> saleList = (ArrayList<SaleReturnPmo>) maps.get("srpSaleMap");
						data.setSaleReturnList(saleList);
					}
					if (maps.get("srpReturnMap") != null) {
						List<SaleReturnPmo> saleList = (ArrayList<SaleReturnPmo>) maps.get("srpReturnMap");
						data.setReturnList(saleList);
					}
					if (child.getData() != null) {
						data.setStaticSalesData(child.getData()); // 业态数据的汇总
					}
					if (child.getData().getIndust() != null) {
						List<StaticSalesIndustData> industDatas = child.getData().getIndust();
						data.setStaticSalesIndustDatas(industDatas);
					}

					LevelDynamiSalesData salesData = levelDynamiSalesData.getDynamiSalesDatas().get(i);
					if (salesData.getData() != null) {
						data.setLevelDynamiSalesData(salesData.getData());
						data.setDynamiExtend(salesData.getData().getDynamiExtend());
					}
					levelDatas.add(data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return levelDatas;
	}

	/**
	 * 
	 * returnPlant:回款计划，销售计划<br/>
	 *
	 * 
	 * @author Administrator
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "returnPlant")
	public @ResponseBody Map<String, Object> returnPlant(Long projectId, Long premisesId) {
		return querySaleReturn(projectId, premisesId);
	}

	/**
	 * 
	 * loadIndust:加载业态信息. <br/>
	 *
	 * @author Administrator
	 * @param id
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "loadIndust")
	public @ResponseBody ProjectPremisesIndustData loadIndust(Long id) {
		Response<ProjectPremisesIndustData> response = projectPremisesIndustDataServiceFacade.findById(id);
		if (response.getEntity() != null) {
			Response<BaseCodeValue> baseCodeValue = baseCodeValueServiceFacade
					.findById(new Long(response.getEntity().getIndustMark()));
			if (baseCodeValue != null && baseCodeValue.getEntity() != null) {
				response.getEntity().setIndustType(baseCodeValue.getEntity().getTypeId().toString());
				ProjectPremisesIndustDataVersionDto versionQuery = new ProjectPremisesIndustDataVersionDto();
				versionQuery.setIndustId(response.getEntity().getId());
				ResponseList<ProjectPremisesIndustDataVersion> vesList = premisesIndustDataVersionServiceFacade
						.findByDto(versionQuery);
				if (vesList.isSuccess() && vesList.getEntity() != null && vesList.getEntity().size() > 0) {
					List<ProjectPremisesIndustDataVersion> array = vesList.getEntity();
					for (ProjectPremisesIndustDataVersion obj : array) {
						obj.setVersionVal(VersionEnum.getByDescription(obj.getVersionName()).getCode() + "");
					}
					response.getEntity().setVersion(array);
				}

			}
			return response.getEntity();
		}
		return null;
	}

	/**
	 * 
	 * deleteIndustInfo:删除业态. <br/>
	 * 
	 * @author Administrator
	 * @param id
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "deleteIndustInfo")
	public @ResponseBody AjaxRes deleteIndustInfo(Long id) {
		AjaxRes ar = getAjaxRes();
		Response<Integer> response = projectPremisesIndustDataServiceFacade.deleteByPrimaryKey(id);
		if (response.getEntity() == null) {
			ar.setRes(Const.FAIL);
		} else {
			ar.setRes(Const.SUCCEED);
		}
		return ar;
	}

	/**
	 * 
	 * bindReceivables:(绑定收款). <br/>
	 * 
	 * @author Administrator
	 * @param projectId
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "bindReceivables")
	public @ResponseBody AjaxRes bindReceivables(Long projectId) {
		AjaxRes ar = getAjaxRes();
		ProjectDto dto = new ProjectDto();
		dto.setId(projectId);
		dto.setBindReceivables("0");
		Response<Integer> response = projectServiceFacade.updateByPrimaryKey(dto, true);
		if (response.isSuccess()) {
			ar.setRes(Const.SUCCEED);
		} else {
			ar.setRes(Const.FAIL);
		}
		return ar;
	}

	/**
	 * 
	 * toBudingIndust:(项目分期楼栋业态数据汇总). <br/>
	 *
	 * @author Administrator
	 * @param projectId
	 * @param premisesId
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "toBudingIndust")
	public ModelAndView toBudingIndust(Long projectId, Long premisesId, String buildIndustType, String industType) {
		ModelAndView mv = new ModelAndView("/estate/projectPremises/budingIndust");
		ResponseList<ProjectPremisesIndustData> responseList = projectPremisesIndustDataServiceFacade
				.queryIndustByBuilding(projectId, premisesId, buildIndustType);
		ResponseList<ProjectPremisesIndustData> industDataResponse = projectPremisesIndustDataServiceFacade
				.queryIndustSum(projectId, premisesId, industType);
		mv.addObject("industDataList", responseList.getEntity());
		mv.addObject("industData", industDataResponse.getEntity());
		return mv;
	}

	@RequestMapping(value = "queryDynamiValue")
	@ResponseBody
	public HashMap<String, BigDecimal> queryDynamiValue(Long projectId, Long premiseId, String month,
			String industType) {
		return projectServiceFacade.queryDynamiValue(projectId, premiseId, month, industType);
	}

	@RequestMapping(value = "pmoPage")
	public ModelAndView pmoPage() {
		User user = ShiroUtil.getCurrentUser();
		return new ModelAndView("/estate/project/pmoPage").addObject("userId", user.getId());
	}
}
